package com.wjv.example.spbt.mybatis.mapper;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;

/**
 * <p>Title: dd</p>
 *
 * @author wjv
 * @date 2021/4/12 11:34
 * @description
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
@Component
public class MyIntercepts implements Interceptor {

    private final String create_time = "create_time";

    private final String update_time = "update_time";

    private final String created_by = "created_by";

    private final String logic_status = "logic_status";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println(invocation);
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();

        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

        String id = mappedStatement.getId();

        if (SqlCommandType.INSERT.equals(mappedStatement.getSqlCommandType())) {
            BoundSql boundSql = statementHandler.getBoundSql();

            String sql = boundSql.getSql();
            String newSql = "INSERT INTO dict_genre\n" +
                    " (genre_name, create_time)\n" +
                    "VALUES (? , NOW())";


            Field field = boundSql.getClass().getDeclaredField("sql");
            field.setAccessible(true);
            field.set(boundSql, newSql);
        }

        return invocation.proceed();
    }
}
